<template>
  <div class="ratings-container">
    <h1>我的评价</h1>
    
    <div class="ratings-summary">
      <el-card class="rating-summary-card">
        <div class="summary-content">
          <div class="score-container">
            <div class="avg-score">{{ riderInfo.rating || '5.0' }}</div>
            <div class="score-text">综合评分</div>
          </div>
          <div class="statistics">
            <div class="stat-item">
              <span class="stat-value">{{ riderInfo.completedOrderCount || 0 }}</span>
              <span class="stat-label">已完成订单</span>
            </div>
            <div class="stat-item">
              <span class="stat-value">{{ ratingStats.excellentCount || 0 }}</span>
              <span class="stat-label">好评数量</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <div class="ratings-filter">
      <el-select v-model="filterScore" placeholder="评分筛选" @change="handleFilterChange">
        <el-option label="全部评分" value=""></el-option>
        <el-option label="5星 (很好)" value="5"></el-option>
        <el-option label="4星 (不错)" value="4"></el-option>
        <el-option label="3星 (一般)" value="3"></el-option>
        <el-option label="2星 (较差)" value="2"></el-option>
        <el-option label="1星 (很差)" value="1"></el-option>
      </el-select>
    </div>
    
    <el-card v-if="loading">
      <div v-for="i in 3" :key="i" class="skeleton-item">
        <el-skeleton animated :rows="2" />
      </div>
    </el-card>
    
    <div v-else-if="ratingList.length === 0" class="no-data">
      <el-empty description="暂无评价数据"></el-empty>
    </div>
    
    <div v-else class="ratings-list">
      <el-card v-for="item in ratingList" :key="item.id" class="rating-item">
        <div class="rating-header">
          <span class="order-info">订单 #{{ item.orderNo }}</span>
          <span class="rating-date">{{ formatDate(item.createdTime) }}</span>
        </div>
        <div class="rating-content">
          <div class="rating-score">
            <el-rate
              v-model="item.rating"
              disabled
              show-score
              text-color="#ff9900">
            </el-rate>
          </div>
          <div class="rating-comment" v-if="item.comment">
            {{ item.comment }}
          </div>
          <div class="rating-comment" v-else>
            <span class="no-comment">用户未留下评价内容</span>
          </div>
        </div>
      </el-card>
    </div>
    
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getRiderRatings, getRiderDetail } from '@/api/rider';
import { mapState } from 'vuex';

export default {
  name: 'RiderRatings',
  data() {
    return {
      loading: false,
      ratingList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filterScore: '',
      riderInfo: {},
      ratingStats: {
        excellentCount: 0, // 好评（4-5星）数量
        goodCount: 0,      // 中评（3星）数量
        badCount: 0        // 差评（1-2星）数量
      },
      userId: null
    };
  },
  computed: {
    ...mapState({
      riderId: state => state.userInfo.id || null
    })
  },
  created() {
    // 从localStorage中直接获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    console.log('本地存储的用户信息:', userInfo);
    
    if (userInfo && userInfo.id) {
      // 如果本地存储有用户ID，优先使用
      this.userId = userInfo.id;
      console.log('使用本地存储的用户ID:', this.userId);
    } else if (this.riderId) {
      // 如果vuex中有用户ID，使用vuex的
      this.userId = this.riderId;
      console.log('使用vuex的用户ID:', this.userId);
    } else {
      console.warn('找不到用户ID');
      this.$message.warning('请先登录');
      return;
    }
    
    // 加载数据
    this.loadRiderInfo();
    this.loadRatings();
  },
  methods: {
    // 加载骑手信息
    loadRiderInfo() {
      // 使用userId而不是riderId
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      console.log('加载骑手信息, userId:', this.userId);
      
      getRiderDetail(this.userId)
        .then(res => {
          if (res.code === 200) {
            console.log('获取骑手信息成功:', res.data);
            this.riderInfo = res.data;
          } else {
            console.error('获取骑手信息API返回错误:', res.message);
            this.$message.error(res.message || '获取骑手信息失败');
          }
        })
        .catch(err => {
          console.error('获取骑手信息错误', err);
          this.$message.error('获取骑手信息失败');
        });
    },
    
    // 加载评价列表
    loadRatings() {
      // 使用userId而不是riderId
      if (!this.userId) {
        this.$message.warning('请先登录');
        return;
      }
      
      console.log('加载评价列表, userId:', this.userId, '筛选:', this.filterScore);
      
      this.loading = true;
      
      getRiderRatings(this.userId, {
        page: this.currentPage,
        size: this.pageSize,
        rating: this.filterScore
      })
        .then(res => {
          console.log('评价列表API返回:', res);
          if (res.code === 200) {
            this.ratingList = res.data.records || [];
            this.total = res.data.total || 0;
            
            // 计算评价统计
            this.calculateRatingStats(res.data.statistics || {});
            
            console.log('评价列表数据:', this.ratingList);
            console.log('评价统计:', this.ratingStats);
          } else {
            console.error('获取评价列表API返回错误:', res.message);
            this.$message.error(res.message || '获取评价列表失败');
          }
        })
        .catch(err => {
          console.error('获取评价列表错误', err);
          this.$message.error('获取评价列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 计算评分统计
    calculateRatingStats(statistics) {
      this.ratingStats = {
        excellentCount: statistics.excellentCount || 0,
        goodCount: statistics.goodCount || 0,
        badCount: statistics.badCount || 0
      };
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hour = d.getHours().toString().padStart(2, '0');
      const minute = d.getMinutes().toString().padStart(2, '0');
      
      return `${year}-${month}-${day} ${hour}:${minute}`;
    },
    
    // 处理筛选变化
    handleFilterChange() {
      this.currentPage = 1;
      this.loadRatings();
    },
    
    // 处理每页数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadRatings();
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadRatings();
    }
  }
};
</script>

<style scoped>
.ratings-container {
  padding: 20px;
}

.ratings-summary {
  margin-bottom: 20px;
}

.rating-summary-card {
  background-color: #f8f9fa;
}

.summary-content {
  display: flex;
  align-items: center;
}

.score-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 30px;
  padding: 10px;
  border-right: 1px solid #e6e6e6;
}

.avg-score {
  font-size: 36px;
  font-weight: bold;
  color: #ff9900;
}

.score-text {
  font-size: 14px;
  color: #666;
}

.statistics {
  display: flex;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.ratings-filter {
  margin-bottom: 20px;
}

.ratings-list {
  margin-bottom: 20px;
}

.rating-item {
  margin-bottom: 15px;
}

.rating-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.rating-content {
  padding: 5px 0;
}

.rating-comment {
  margin-top: 10px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #666;
}

.no-comment {
  color: #999;
  font-style: italic;
}

.skeleton-item {
  margin-bottom: 20px;
}

.no-data {
  margin: 50px 0;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 